package middle;

public class Solution_142 {

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head, fast = head.next;
        while (fast != null && slow != fast) {
            slow = slow.next;
            fast = fast.next;
            if (fast != null) {
                fast = fast.next;
            }
        }
        if (fast != null) {
            fast = fast.next;
            ListNode node = head;
            while (node != fast) {
                node = node.next;
                fast = fast.next;
            }
            return node;
        }
        return null;
    }

    public static void main(String[] args) {
        Solution_142 model = new Solution_142();
        ListNode head = new ListNode(3);
        head.next = new ListNode(2);
        head.next.next = new ListNode(0);
        head.next.next.next = new ListNode(-4);
        head.next.next.next.next = head.next;
        ListNode listNode = model.detectCycle(head);
        System.out.println();
    }

    static class ListNode {

        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
